﻿/**
 *  课时页面
 */
import React, { Component } from 'react'
import {
    StyleSheet,
    View,
    Text,
    ScrollView,
    TouchableOpacity,
    Image,
    AsyncStorage,
    BackHandler
} from 'react-native';
import { Toast } from 'teaset'
import BuyedCommon from '../../component/BuyedCommon'
import Tab from '../../component/Tab'
const Dimensions = require('Dimensions');
const { width,height } = Dimensions.get('window');
import BottomBarLimit from '../../common/BottomBarLimit';
import NavigatorBar from '../../common/NavigationBar';
import Loading from '../../common/Loading'
import BaseBridge from '../../common/Native/BaseBridge';
import ReplayComp from './comps/ReplayComp';
import AskQuestionComp from './comps/AskQuestionComp';
import { getCoursePartById, letParentEnroll, listParents} from '../../api/my';
import {setSpText,setHW} from '../../component/ScreenUtil'
var that;
export default class KeShiIndex extends Component {
    constructor(props) {
        super(props);
        // console.log(props,'prpo-----------------')
        this.params = props.navigation.state.params ? props.navigation.state.params: {'id': global.ECourseConstant.map["entryLessonId"]};
        this.state = {
            loading: true,
            tabList: [],
            parentListId: [],//家长id数组
            showFootTab:true,//一定默认true
            showFootBuyStatus: false,//学生端：收费&&未购买&&没报名显示底部的付款 为true；家长：收费&&未购买
            headerInfor: {},
            KeShiPeriodsList: null,
            periodsBorder: false,
            // 问答区：
            isShowReplayInput: false,//是否展示回复框
            showAskQuestionInput:false,
            comment_id: null,//当前评论的id
            // behaviorKey: 'position',
        };
        that=this;
    }
    // 获取传过来的课时id 获取课时列表
    componentDidMount() {
        this.listParentsAndreSearch()
        BackHandler.addEventListener('hardwareBackPress', that.handleBack);
    }
    handleBack() {
        if(that.props&&that.props.navigation&&that.props.navigation.state&&that.props.navigation.state.params&&that.props.navigation.state.params["fromPaySucess"])
        {
            //如果是支付成功页过来的
            that.props.navigation.navigate('HomePage');
            return true;
        }else
        {
            that.goBack();
            return true;
        }
    }
    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', that.handleBack)
    }
    //第二次进来走这里
    componentWillReceiveProps(curProps) {
        let curPropsKeshiId=curProps.navigation.state.params.id;
        this.listParentsAndreSearch(curPropsKeshiId);
    }
    listParentsAndreSearch(curPropsKeshiId){
        this.setState({loading: true});
        let obj = {
            STUDENTID: global.ECourseConstant.userInfo.studentId
        }
        listParents(obj).then((res) => {
            this.setState({ parentListId: res });//获取家长id数组
            this._getCoursePartById(curPropsKeshiId)
        });
    }
    // 购买前的--课时接口
    _getCoursePartById(curPropsKeshiId) {
        var json = {
            "ID": curPropsKeshiId?curPropsKeshiId:this.params.id,//课时id
            "CREATOR": global.ECourseConstant.userInfo.uuid,//登陆app
            "LISTPARENTIDS": this.state.parentListId//家长id
        }
        getCoursePartById(json).then(res => {
            this.setState({loading: false});
           
            let course=res.COURSEDTO;//课时中的课程信息
            res.PIC = course.PIC;//课时中来自课程的课程图 课时pic也是这个
            res.COURSE_NAME = course.COURSE_NAME;//课程名字 //课时中来自课程
            res.SUBJECTNAME = course.SUBJECTNAME;//学科//headerInfor
            res.LISTGRADE = course.LISTGRADE;//年级数组//headerInfor
            res.PERIODNAME = course.PERIODNAME;//学段 初中....
            res.USERNAME = course.USERNAME;//l老师名字 //课时中来自课程
            res.ToTalMONEY = course.MONEY;//课程的总价格///课时中来自课程
            res.STOP_TIME = course.STOP_TIME;//课程的截至时间//headerInfor
            this.ShowTab(res)//根据该课时的收费和购买情况展示不同的tab页面
            this.setState({loading: false,headerInfor: res,KeShiPeriodsList: [res]});
            global.log(this.state.KeShiPeriodsList, '整合后的课时的数据KeShiPeriodsList')
        })
    }
    // 允许展示底部购买的tab flag为true 但tab切换时决定
    showFootBuyFun(flag){
        this.setState({showFootTab:flag})
    }
    // 刷新
    ResetSearch() {
        this._getCoursePartById()
    }
    // 是否展示回复框
    updateShowInput = (flag,comment_id) => {
        this.setState({
            isShowReplayInput: flag,
            comment_id: comment_id,
        })
    }
    // 展示向老师提问
    showAskQuestionInput(flag){
        this.setState({showAskQuestionInput:flag})
    }
    render() {
        return (
            <View style={styles.lessonsContainer}>
                <NavigatorBar
                    style={styles.navigatorBar}
                    title={'课时详情'}
                    leftButton={this.renderLeftButton(require('../../assets/imgs/back.png'))}
                />
                <ScrollView
                    showsVerticalScrollIndicator={false}
                >
                    {this.state.tabList&&this.state.tabList.length?
                    <View>
                        <BuyedCommon
                            isKeshi={true}
                            headerInfor={this.state.headerInfor}
                            {...this.props}
                        />
                        <Tab
                            ref="children"
                            updateShowInput={(flag,comment_id)=>this.updateShowInput(flag,comment_id)}
                            showAskQuestionInput={(flag) => this.showAskQuestionInput(flag)}    
                            tabList={this.state.tabList}
                            showFootBuyFun={(flag) => this.showFootBuyFun(flag)}
                            KeShiPeriodsList={this.state.KeShiPeriodsList}
                            headerInfor={this.state.headerInfor}
                            courseId={this.params.courseId}
                            ResetSearch={(name) => this.ResetSearch(name)}
                            {...this.props}>
                        </Tab>
                    </View>:null}
                    {this.loading()}
                    <BottomBarLimit />
                </ScrollView>
                {/* 回复 */}
                {this.state.isShowReplayInput ? 
                <ReplayComp ref="ReplayComp" 
                            updateShowInput={(flag)=>this.updateShowInput(flag)} 
                            CommentId={this.state.comment_id}
                            TabFun={this.TabFun}
                            {...this.props}/>: null}
                {/* 向老师提出问题 */}
                {this.state.showAskQuestionInput&&!this.state.isShowReplayInput ? 
                <AskQuestionComp dataInfor={this.state.KeShiPeriodsList} 
                TabFun={this.TabFun} {...this.props}/>:null}
                {/* 底部付款 */}
                {this.showFootBuy()}
            </View>
        )
    }
    // 加载loading
	loading(){
		if(this.state.loading){
			return(
				<View style={{height:height - 100}}>
					<Loading/>
				</View>
			)
		}
    }
    // 调用 tab这个子组件 的onRef方法 最后刷新数据
    TabFun= () =>{
        this.refs.children.onRef()
    }
    //学生端：收费&&未购买&&没报名显示底部的付款 showFootBuy为true；家长：收费&&未购买
    // showFootBuy() 是收费&&未购买
    showFootBuy() {
        if (this.state.showFootTab&&this.state.KeShiPeriodsList&&this.state.showFootBuyStatus) {//showFootBuyStatus是收费且未购买
            return (
                <View style={styles.barBottom}>
                    <View style={styles.pricePay}>
                        <View style={styles.priceWrapper}>
                            <Text style={styles.priceDiscountText}>合计:</Text>
                            <View style={styles.priceNumber}>
                                <Text style={styles.numPrifix}>¥</Text>
                                <Text style={styles.number}>{this.state.KeShiPeriodsList && this.state.KeShiPeriodsList[0].MONEY}</Text>
                            </View>
                        </View>
                        {
                            this.state.KeShiPeriodsList ? this.btnStatus(this.state.KeShiPeriodsList[0]) : null
                        }
                    </View>
                </View>
            )
        }
    }
    // btnStatus是在是收费&&未购买的前提下
    btnStatus(data) {
        // 学生端
        var userType = global.ECourseConstant.userInfo.loginType;//学生
        if (userType == '4') {
            if (data.ISENROLL == "" || data.ISENROLL == "0") {//未报名的
                return (
                    <View style={styles.stylepayLessons}>
                        <Text style={styles.buttonText} onPress={() => this._letParentEnroll(data)}>让家长报名</Text>
                    </View>
                )
            } else {
                return (
                    <View style={[styles.stylepayLessons, styles.buttonTextDisableBox]}>
                        <Text style={styles.buttonTextDisable}>家长正在购买中</Text>
                    </View>
                )
            }
        }
        // 如果是家长
        if (userType == '1' || userType == '3') {
            return (
                <View style={styles.stylepayLessons}>
                    <Text style={styles.buttonText} onPress={() => this.btnParentSubmit()}>立即报名</Text>
                </View>
            )

        }
    }
    // 家长端： 立即购买
    btnParentSubmit() {
        let payCourseInfo = {
            BASICINFO: {},
            LISTCOURSE: [],
            toPage: 'KeShiIndex',
        }
        let data = this.state.KeShiPeriodsList[0];
        payCourseInfo.BASICINFO.COURSE_NAME = data.COURSE_NAME//课程名字
        payCourseInfo.BASICINFO.STOP_TIME = data.STOP_TIME//截至时间
        payCourseInfo.BASICINFO.TEACHER_NAME = data.USERNAME//老师
        payCourseInfo.BASICINFO.COURSE_ID = data.COURSEID//课程id
        payCourseInfo.BASICINFO.TOTLE_MONEY = data.MONEY//课程id
        let obj = {
            "COURSE_TYPE": "1",//0 是课程1是课时
            "COURSE_ID": data.ID,//课时id
            "MONEY": data.MONEY,//课时的价格
            "COURSE_NAME": data.TITLE//课时的名字
        }
        payCourseInfo.LISTCOURSE.push(obj)
        AsyncStorage.setItem('payCourseInfo', JSON.stringify(payCourseInfo));
        this.props.navigation.navigate("PayScreen");
    }
    // 学生端：学生通知家长 去报名
    _letParentEnroll(data) {
        if(this.state.parentListId.length){
            this.setState({loading: true})
            let json = {
                "COURSEID": data.COURSEID,//课程id
                "COURSEPARTID": [data.ID],//    课时idlist
                "LISTPARENTIDS": this.state.parentListId,//家长idlist app
                "COURSETYPE": "1",//课程类型 0课程 1课时
                "STUDENTID": global.ECourseConstant.userInfo.studentId,//学生id app
            }
            global.log("让家长报名的参数", json)
            letParentEnroll(json).then(res => {
                this.setState({loading: false})
                this.ResetSearch();//刷新数据
                // this.btnStatus(data)
            }).catch(res=>{
                this.setState({ loading: false });
            })
        }else{
            Toast.message("您还没有绑定家长")
        }
    }
    goBack() {

        if(that.props&&that.props.navigation&&that.props.navigation.state&&that.props.navigation.state.params&&that.props.navigation.state.params["fromPaySucess"])
        {
            //如果是支付成功页过来的
            that.props.navigation.navigate('HomePage');
            return;
        }
        if(global.ECourseConstant.eCourseFirstRouter=="KeShiIndex"){
            BaseBridge.backToExue();
        }else{
            this.params&&this.params.refreshPage&&this.params.refreshPage();//返回上一个页面的refreshPage()
            this.props.navigation.goBack();//pop就会返回上一个页面)
        }
        
    }
    // 渲染按钮 返回按钮
    renderLeftButton(image) {
        var that=this;
        return <TouchableOpacity
            style={[global.CommonStyleSheet.NavLeftButton]}
            onPress={() => {
                that.goBack();
            }}>
            <Image
                style={{ width: 34, height: 34 }}
                source={image} />
        </TouchableOpacity>;
    }
    ShowTab(res){
        // IS_FREE 0是收费 1是免费  ISBUY  0是没购买 1是购买
        if(res.IS_FREE=='0'&&res.ISBUY=='0'){//收费 没有购买
            let flag=true;
            let haveQuestionArea=false;
            this.showTreeTab(flag,haveQuestionArea)
        }else{
            if(res.ISNOTPLAY=='-1'){//禁播状态
                let flag=false;
                let haveQuestionArea=false;
                this.showTreeTab(flag,haveQuestionArea)
            }else{
                let flag=false;
                let haveQuestionArea=true;
                this.showTreeTab(flag,haveQuestionArea)
            }
        }
      
    }
    showTreeTab(flag,haveQuestionArea){
        if(haveQuestionArea){
            this.setState({
                showFootBuyStatus:flag,
                tabList: [
                    {
                        tabText: '课时介绍',
                        tabName: 'DetailPeriods',
                    },
                    {
                        tabText: '老师介绍',
                        tabName: 'TeaIntroduction',
                    },
                    {
                        tabText: '问答区',
                        tabName: 'QuestionArea',
                    }
                ],
            })
        }else{
            this.setState({
                showFootBuyStatus:flag,
                tabList: [
                    {
                        tabText: '课时介绍',
                        tabName: 'DetailPeriods',
                    },
                    {
                        tabText: '老师介绍',
                        tabName: 'TeaIntroduction',
                    }
                ],
            })
        }
    }
}
const styles = StyleSheet.create({
    lessonsContainer: {
        flex: 1,
        backgroundColor: '#F7F7F9'
    },
    buttonTextDisableBox: {
        backgroundColor: '#ccc',
    },
    buttonTextDisable: {
        color: '#fff',
    },
    periods: {
        marginTop: 6,
        color: '#999'
    },
    // 底部付款tips
    barBottom: {
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        backgroundColor: '#fff',
        height: setHW(100),
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems: 'center',
        paddingLeft: setHW(20),
        shadowColor: '#000000',
        shadowRadius: 7,
        shadowOpacity: 0.1,
    },
    priceWrapper: {
        flexDirection: 'row',
        alignItems: 'center',
        marginRight: setHW(20),
    },
    priceDiscountText: {
        fontSize: setSpText(26),
        color: '#333',
        marginRight:setHW(8),
    },
    priceNumber: {
        flexDirection: 'row',
        alignItems:'center',
    },
    numPrifix: {
        color: '#FF9920',
        fontSize:setSpText(26),
        marginTop:setHW(4),
    },
    number: {
        fontSize: setSpText(36),
        color: '#FF9920',
        fontWeight: 'bold'
    },
    pricePay: {
        flexDirection: 'row'
    },
    stylepayLessons: {
        width: setHW(276),
        height:setHW(100),
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#FF9920',
    },
    buttonText: {
        color: '#fff',
        fontSize: setSpText(36),
    },
});
